package jzoffer;

import java.util.Arrays;

/**
 * Author:   dengxin
 * Date:     2020/6/17 1:52 下午
 * 旋转数组的最小数字
 * 把一个数组最最开始的若干个元素搬到数组的末尾，称之为数组的旋转
 * 输入：非递减的排序数组的一个旋转，输出旋转数组的最小元素
 * 如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转，输出最小元素1
 * 思路：二分查找
 */
public class jz6 {

    public static void main(String[] args) {
//        int[] array = {6501,6828,6963,7036,7422,7674,8146,8468,8704,8717,9170,9359,9719,9895,9896,9913,9962,154,293,334,492,1323,1479,1539,1727,1870,1943,2383,2392,2996,3282,3812,3903,4465,4605,4665,4772,4828,5142,5437,5448,5668,5706,5725,6300,6335};
        int[] array = {1,1,1,0,1};
        int result = minNumberInRotateArray(array);
        System.out.println(result);
    }

    private static int minNumberInRotateArray(int[] array) {
        //边界条件
        int length = array.length;
        if (length == 0) {
            return 0;
        }
        //二分查找
        int low = 0, high = length-1;
        while (high > low) {
            int mid = (low+high)/2;
            //如果mid>high，那么最小元素肯定在[mid+1,high]
            if (array[mid] > array[high]) {
                low = mid+1;
            }
            //如果mid<high，那么最小元素肯定在[first,mid]
            else if (array[mid] < array[high]) {
                high = mid;
            }
            //如果mid=high，那么最小原语肯定在[mid,high-1]，考虑{1,1,1,0,1}这种情况
            else  {
                high--;
                low = mid;
            }
        }
        return array[high];
    }
}
